package com.epalmpay.controller.channel.trade;

import com.epalmpay.commom.BaseController;
import com.epalmpay.dto.system.ShopListOutDTO;
import com.epalmpay.entity.MachineWasher;
import com.epalmpay.entity.MachineWasherLog;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.service.machinewasher.IMachineWasherService;
import com.epalmpay.service.shop.IShopService;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.system.BaseOutDTO;
import com.epalmpay.dto.system.PageDTO;
import com.epalmpay.dto.system.TradeOfflineBaseOutDTO;
import com.epalmpay.dto.trade.DeviceOfflineRecordInDTO;
import com.epalmpay.dto.trade.DeviceOfflineRecordListOutDTO;
import com.epalmpay.dto.trade.DeviceOfflineRecordOutDTO;
import com.epalmpay.dto.yunliu.obd.ObdSmOutDTO;
import com.epalmpay.entity.Page;
import com.epalmpay.entity.TradeOffline;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.service.management.ITemplateMailSendService;
import com.epalmpay.service.posapi.PosApiService;
import com.epalmpay.service.posapi.PosApiServiceTransactional;
import com.epalmpay.service.trade.IDevOfflineRecordService;
import com.epalmpay.util.Const;
import com.epalmpay.util.Tools;
import com.epalmpay.util.payplat.DateUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wucongpeng on 2017/5/4.
 */
@Controller
@RequestMapping(value = "/channel/device")
public class DeviceOfflineRecordController extends BaseController {


    @Resource
    private IDevOfflineRecordService devOfflineRecordService;
    @Resource
    private PosApiService posApiService;
    
    @Resource
    private PosApiServiceTransactional posApiServiceTransactional;

    @Resource
    private IShopService shopService;
    
    @Autowired 
    @Lazy
	private ITemplateMailSendService templateMailSendService;

    @Resource
    private IMachineWasherService machineWasherService;



    /**
     * 显示线下交易记录分页列表
     * @param offlineRecordInDTO
     * @param pageDTO
     * @return
     */
    @RequestMapping(value = "/offlineRecordList")
    @ResponseBody
    public DeviceOfflineRecordListOutDTO listOfflineRecord(DeviceOfflineRecordInDTO offlineRecordInDTO, PageDTO pageDTO){
        DeviceOfflineRecordListOutDTO offlineRecordListOutDTO = new DeviceOfflineRecordListOutDTO();
        ArrayList<DeviceOfflineRecordOutDTO> offlineRecordOutDTOs=new ArrayList<DeviceOfflineRecordOutDTO>();
        try {

            Page page= Tools.pageEmtity(pageDTO);

            List<TradeOffline> list=devOfflineRecordService.listOfflineRecords(offlineRecordInDTO, page);
            for (int i = 0; i < list.size(); i++) {

                DeviceOfflineRecordOutDTO dtos =new DeviceOfflineRecordOutDTO();
//                PropertyCopyUtil.copyPropertiesExclude(list.get(i),dtos);

                dtos.setId(list.get(i).getId());
                dtos.setGmtCreate(list.get(i).getGmtCreate());
                dtos.setGmtModified(list.get(i).getGmtModified());
                dtos.setDiscountAmount(list.get(i).getDiscountAmount()+list.get(i).getBonusValue());//优惠金额 = 折扣+ 使用优惠券的
                dtos.setGroupId(list.get(i).getGroupId());
                dtos.setOrderAmount(list.get(i).getOrderAmount());
                dtos.setOrderId(list.get(i).getOrderId());
                dtos.setPayerId(list.get(i).getPayerId());
//                dtos.setPayerName(list.get(i).getPayerName());
                if (list.get(i).getPayType() != null) {
                    dtos.setPayType(list.get(i).getPayType());
                }
                dtos.setRealAmount(list.get(i).getRealAmount());
                dtos.setReceiverId(list.get(i).getReceiverId());
                dtos.setReceiverName(list.get(i).getReceiverName());
                dtos.setTransactionStatus(list.get(i).getTransactionStatus());
                dtos.setTransactionType(list.get(i).getTransactionType());
                dtos.setFee(list.get(i).getFee());
                dtos.setBonusAmount(list.get(i).getBonusAmount());
                dtos.setTickName(list.get(i).getName());
                dtos.setNumber(list.get(i).getNumber());
//                dtos.setBonusValue(list.get(i).getBonusValue());//去掉 直接加到优惠金额字段里了 方便做导出
                if (list.get(i).getTransactionType() != null && list.get(i).getTransactionType() == 15){
                    dtos.setPayerName(offlineRecordInDTO.getGroupName());
                }else{
                    dtos.setPayerName(list.get(i).getPayerName());
                }
                offlineRecordOutDTOs.add(dtos);
                offlineRecordListOutDTO.setDeviceOfflineRecordOutDTOList(offlineRecordOutDTOs);
            }

                offlineRecordListOutDTO.setPage(page);
            offlineRecordListOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
            return offlineRecordListOutDTO;

        } catch (ApplicationException ae) {
            offlineRecordListOutDTO.setErrorCode(ae.errCode, ae.errMsg);
            ae.printStackTrace();
        }
        catch (Exception e) {
            offlineRecordListOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
            e.printStackTrace();
        }
        return offlineRecordListOutDTO;
    }


    /**
     * 通过用户id查询交易详情
     *
     */
    @RequestMapping(value="/offlineRecordFindById")
    @ResponseBody
    public DeviceOfflineRecordOutDTO  findByOfflineRecord(DeviceOfflineRecordInDTO deviceOfflineRecordInDTO){
        DeviceOfflineRecordOutDTO deviceOfflineRecordOutDTO=new DeviceOfflineRecordOutDTO();
        TradeOffline offline=new TradeOffline();
        try {
            offline.setId(deviceOfflineRecordInDTO.getId());
            offline.setMemberId(deviceOfflineRecordInDTO.getMemberId());
            TradeOffline offlineRecord=devOfflineRecordService.offlinefindById(offline);
            if(offlineRecord!=null){

                //如何是退款查询出原始订单号
                if(offlineRecord.getTransactionType() != null) {
                    if (offlineRecord.getTransactionType() == BizEnum.TransactionType.Refund.getType()) {
                        String oldOrderId = devOfflineRecordService.offlineOldOrderIdfindByOrderId(offlineRecord.getOldOrderId());
                        if (!Tools.isEmpty(oldOrderId)) {
                            deviceOfflineRecordOutDTO.setOldOrderId(oldOrderId);
                        }
                    }
                }

                deviceOfflineRecordOutDTO.setId(offlineRecord.getId());
                deviceOfflineRecordOutDTO.setGmtCreate(offlineRecord.getGmtCreate());
                deviceOfflineRecordOutDTO.setGmtModified(offlineRecord.getGmtModified());
                deviceOfflineRecordOutDTO.setDiscountAmount(offlineRecord.getDiscountAmount());
                deviceOfflineRecordOutDTO.setGroupId(offlineRecord.getGroupId());
                deviceOfflineRecordOutDTO.setOrderAmount(offlineRecord.getOrderAmount());
                deviceOfflineRecordOutDTO.setOrderId(offlineRecord.getOrderId());
                deviceOfflineRecordOutDTO.setPayerId(offlineRecord.getPayerId());
                deviceOfflineRecordOutDTO.setPayerName(offlineRecord.getPayerName());
                deviceOfflineRecordOutDTO.setPayType(offlineRecord.getPayType());
                deviceOfflineRecordOutDTO.setRealAmount(offlineRecord.getRealAmount());
                deviceOfflineRecordOutDTO.setReceiverId(offlineRecord.getReceiverId());
                deviceOfflineRecordOutDTO.setReceiverName(offlineRecord.getReceiverName());
                deviceOfflineRecordOutDTO.setTransactionStatus(offlineRecord.getTransactionStatus());
                deviceOfflineRecordOutDTO.setTransactionType(offlineRecord.getTransactionType());
                deviceOfflineRecordOutDTO.setMerchantNo(offlineRecord.getMerchantNo());
                deviceOfflineRecordOutDTO.setTerminalNo(offlineRecord.getTerminalNo());
                deviceOfflineRecordOutDTO.setTermSerial(offlineRecord.getTermSerial());
                deviceOfflineRecordOutDTO.setMemberId(offlineRecord.getMemberId());
                deviceOfflineRecordOutDTO.setMemberName(offlineRecord.getMemberName());
                deviceOfflineRecordOutDTO.setGradeName(offlineRecord.getGradeName());
                deviceOfflineRecordOutDTO.setFromName(offlineRecord.getFromName());
                deviceOfflineRecordOutDTO.setCouponCount(offlineRecord.getCouponCount());
                deviceOfflineRecordOutDTO.setCouponInfo(offlineRecord.getCouponInfo());
                deviceOfflineRecordOutDTO.setAdjustAmount(offlineRecord.getAdjustAmount());
                deviceOfflineRecordOutDTO.setBackAmount(offlineRecord.getBackAmount());
                deviceOfflineRecordOutDTO.setBonusAmount(offlineRecord.getBonusAmount());
                deviceOfflineRecordOutDTO.setBonusValue(offlineRecord.getBonusValue());
                deviceOfflineRecordOutDTO.setCardNo(offlineRecord.getCardNo());
                deviceOfflineRecordOutDTO.setTransOrderNo(offlineRecord.getTransOrderNo()==null?"":offlineRecord.getTransOrderNo());
                if(offlineRecord.getMemo() !=null){
                    deviceOfflineRecordOutDTO.setMemo(offlineRecord.getMemo());
                }

                //洗衣机的账号去查机器编号和地址
                if(deviceOfflineRecordInDTO.getGroupId()==16){
                    MachineWasherLog machineWasherLog = machineWasherService.queryWashInfoByOrderId(offlineRecord.getOrderId());
                    if(machineWasherLog !=null){
                        deviceOfflineRecordOutDTO.setAddress(machineWasherLog.getAddress()==null?"":machineWasherLog.getAddress());
                        deviceOfflineRecordOutDTO.setBoardid(machineWasherLog.getBoardid()==null?"":machineWasherLog.getBoardid());
                    }
                }

//                PropertyCopyUtil.copyPropertiesExclude(offlineRecord,deviceOfflineRecordOutDTO);
                deviceOfflineRecordOutDTO.setErrorCode(Rescode.SUCCESS, "查询成功");
                return deviceOfflineRecordOutDTO;
            }else{
                deviceOfflineRecordOutDTO.setErrorCode("-1", "未查询到记录");
            }
        } catch (Exception e) {
            deviceOfflineRecordOutDTO.setErrorCode("-1", "处理出现异常");
            e.printStackTrace();
        }
        deviceOfflineRecordOutDTO.setErrorCode("-2", "处理失败");
        return deviceOfflineRecordOutDTO;
    }

    /**
     * 通过用户id查询交易详情
     *
     */
    @RequestMapping(value="/offlineRecordFindByOrderId")
    @ResponseBody
    public ObdSmOutDTO offlineRecordFindByOrderId(@RequestBody DeviceOfflineRecordOutDTO dto){
        ObdSmOutDTO obdSmOutDTO=new ObdSmOutDTO();
        TradeOffline offline=new TradeOffline();
        try {
            offline.setOrderId(dto.getOrderId());

            TradeOffline offlineRecord=devOfflineRecordService.offlinefindByOrderId(offline);
            if(offlineRecord!=null){
                obdSmOutDTO.setOrderId(offlineRecord.getOrderId());
                obdSmOutDTO.setPayType(offlineRecord.getPayType());
                obdSmOutDTO.setRealAmount(offlineRecord.getRealAmount());
                obdSmOutDTO.setMemo(offlineRecord.getMemo());
                obdSmOutDTO.setTime(DateUtils.getDateTimeString("yyyy-MM-dd hh:mm:ss", offlineRecord.getGmtModified()));

                obdSmOutDTO.setTransactionStatus(offlineRecord.getTransactionStatus());
                obdSmOutDTO.setErrorCode(Rescode.SUCCESS, "查询成功");
                return obdSmOutDTO;
            }else{
                obdSmOutDTO.setErrorCode("-1", "未查询到记录");
            }
        } catch (Exception e) {
            obdSmOutDTO.setErrorCode("-1", "处理出现异常");
            e.printStackTrace();
        }
        obdSmOutDTO.setErrorCode("-2", "处理失败");
        return obdSmOutDTO;
    }
    
    
    /**
     * 通过用户id查询交易详情
     *
     */
    @RequestMapping(value="/tkReimburse")
    @ResponseBody
    public BaseOutDTO tkReimburse(DeviceOfflineRecordInDTO deviceOfflineRecordInDTO){
    	BaseOutDTO baseOutDTO=new BaseOutDTO();
    	try {
    		TradeOfflineBaseOutDTO tradeOfflineBaseOutDTO=devOfflineRecordService.updateTkReimburse(deviceOfflineRecordInDTO);
	    		if(tradeOfflineBaseOutDTO.getErrorCode().equals(Rescode.SUCCESS)){
	    			
	    			//微信发送模板消息	
	    			if(tradeOfflineBaseOutDTO.getTradeOffline().getPayerId()!=null){
	    				try {
							templateMailSendService.sendTemplate(tradeOfflineBaseOutDTO.getTradeOffline(),  BizEnum.WebTemplateType.template5.getType(),
									tradeOfflineBaseOutDTO.getTradeOffline().getPayerId(),
									tradeOfflineBaseOutDTO.getTradeOffline().getGroupId(), BizEnum.PaymentType.WebChat.getType(),ROOT_HOME_URL);
						} catch (Exception e) {
							logger.info ("模板消息发送失败"+e); 
						}
	    			}
	    			
	    			try {
	    				 posApiService.refundBenefit(tradeOfflineBaseOutDTO.getTradeOffline(), tradeOfflineBaseOutDTO.getTradeOffline().getTransOrderNo());
	    				 posApiServiceTransactional.saveOtherRefund(tradeOfflineBaseOutDTO.getTradeOffline().getTransOrderNo(),
	    						 null, tradeOfflineBaseOutDTO.getTradeOffline().getPayType()!=null?tradeOfflineBaseOutDTO.getTradeOffline().getPayType():0,
	    								 tradeOfflineBaseOutDTO.getTradeOffline());
	    				 baseOutDTO.setErrorCode(Rescode.SUCCESS, "退款成功");
	    	             return baseOutDTO;
					} catch (ApplicationException ae) { 
						ae.printStackTrace();
						baseOutDTO.setErrorCode(Rescode.SUCCESS, "退款成功"+ae.errMsg);
	    	            return baseOutDTO;
					}
					 catch (Exception e) { 
						baseOutDTO.setErrorCode(Rescode.SUCCESS, "退款成功,但退还优惠福利异常");
						e.printStackTrace();
					}
	    			
	    		}else{
	    			baseOutDTO.setErrorCode(Rescode.FAIL, tradeOfflineBaseOutDTO.getErrorMsg());
	    		}
		} catch (ApplicationException ae) { 
			baseOutDTO.setErrorCode(ae.errCode, ae.errMsg);
			ae.printStackTrace();
		}
		 catch (Exception e) { 
			 baseOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "退款出现异常");
			 e.printStackTrace();
		}
        return baseOutDTO;
    }

    /**
     * 门店列表
     * @param deviceOfflineRecordInDTO
     * @return
     */
    @RequestMapping(value="/shopList")
    @ResponseBody
    public ShopListOutDTO listMember(DeviceOfflineRecordInDTO deviceOfflineRecordInDTO){
        ShopListOutDTO shopListOutDTO=new ShopListOutDTO();
        try {
            shopListOutDTO=shopService.listGroupShop(deviceOfflineRecordInDTO.getGroupId());
            shopListOutDTO.setErrorCode(Rescode.SUCCESS, "查询成功");
            return shopListOutDTO;
        } catch (ApplicationException ae) {
            shopListOutDTO.setErrorCode(ae.errCode, ae.errMsg);
            ae.printStackTrace();
        }
        catch (Exception e) {
            shopListOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
            e.printStackTrace();
        }
        return shopListOutDTO;
    }

    /**
     * 门店列表
     * @param deviceOfflineRecordInDTO
     * @return
     */
    @RequestMapping(value="/shopListInThisAgent")
    @ResponseBody
    public ShopListOutDTO shopListInThisAgent(DeviceOfflineRecordInDTO deviceOfflineRecordInDTO){
        ShopListOutDTO shopListOutDTO=new ShopListOutDTO();
        try {
            shopListOutDTO=shopService.listAgentShop(deviceOfflineRecordInDTO.getGroupId(),deviceOfflineRecordInDTO.getAgentId());
            shopListOutDTO.setErrorCode(Rescode.SUCCESS, "查询成功");
            return shopListOutDTO;
        } catch (ApplicationException ae) {
            shopListOutDTO.setErrorCode(ae.errCode, ae.errMsg);
            ae.printStackTrace();
        }
        catch (Exception e) {
            shopListOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
            e.printStackTrace();
        }
        return shopListOutDTO;
    }



}
